package com.dzl.goods;

import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.base.controller.BaseController;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.UploadConstant;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.pojo.dto.WelfareGoodsManageAddDto;
import com.dzl.goods.pojo.query.WelfareGoodsManageQuery;
import com.dzl.goods.pojo.vo.WelfareGoodsDetailVo;
import com.dzl.goods.pojo.vo.WelfareJicaiGoodsManageVo;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.util.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 集采商品(WelfareGoods)表控制层
 * @author liuguanjun
 * @date 2021-12-16 17:14:42
 */
@Slf4j
@RestController
@RequestMapping("/welfareJicaiGoods")
public class WelfareJicaiGoodsController extends BaseController {

    @Autowired
    private WelfareGoodsService welfareGoodsService;

    /**
     * 商品管理列表查询
     * @param query 查询实体类
     * @author liuguanjun
     * @date 2021-12-17 11:15:38
     **/
    @GetMapping("getGoodsListManage")
    public PageUtils<WelfareJicaiGoodsManageVo> getGoodsListManage(WelfareGoodsManageQuery query) {
        query.setIsJicai(CommonConstants.YES);
        PageInfo<WelfareJicaiGoodsManageVo> pageInfo = welfareGoodsService.getWelfareJicaiGoodsListPage(query);
        return new PageUtils<>(pageInfo);
    }


    /**
     * 商品添加
     * @param welfareGoodsManageAddDto 商品添加dto实体类
     * @author liuguanjun
     * @date 2021-12-17 11:16:38
     **/
    @PostMapping("addGoodsManage")
    public JsonResult<Integer> addGoodsManage(@RequestBody WelfareGoodsManageAddDto welfareGoodsManageAddDto) {
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        welfareGoodsManageAddDto.setIsJicai(CommonConstants.YES);
        welfareGoodsManageAddDto.setGoodsType(9);
        welfareGoodsManageAddDto.setOptType(1);
        welfareGoodsManageAddDto.setPartitionId(-1);
        welfareGoodsManageAddDto.setSupplierId(-1);
        welfareGoodsManageAddDto.setFirstClassifyId(-1);
        welfareGoodsManageAddDto.setSecondClassifyId(-1);
        welfareGoodsManageAddDto.setThirdClassifyId(-1);
        welfareGoodsManageAddDto.setGoodsDetail("集采商品详情");
        Map<String, Object> resMap = welfareGoodsService.addGoodsManage(welfareGoodsManageAddDto,getAdminInfo());
        if (resMap.get("code").equals(1)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 商品及规格修改
     * @param welfareGoodsManageAddDto 商品修改dto实体类
     * @author liuguanjun
     * @date 2021-12-17 11:20:38
     **/
    @PostMapping("updateGoodsManage")
    public JsonResult<Integer> updateGoodsManage(@RequestBody WelfareGoodsManageAddDto welfareGoodsManageAddDto) {
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        welfareGoodsManageAddDto.setIsJicai(CommonConstants.YES);
        welfareGoodsManageAddDto.setGoodsType(9);
        welfareGoodsManageAddDto.setOptType(1);
        welfareGoodsManageAddDto.setPartitionId(-1);
        welfareGoodsManageAddDto.setSupplierId(-1);
        welfareGoodsManageAddDto.setFirstClassifyId(-1);
        welfareGoodsManageAddDto.setSecondClassifyId(-1);
        welfareGoodsManageAddDto.setThirdClassifyId(-1);
        welfareGoodsManageAddDto.setGoodsDetail("集采商品详情");
        Map<String, Object> resMap = welfareGoodsService.updateGoodsManage(welfareGoodsManageAddDto);
        if (resMap.get("code").equals(1)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 获取商品详细信息
     * @param goodsId 商品id
     * @author liuguanjun
     * @since 2021-12-17 11:23:38
     **/
    @GetMapping(value = "getGoodsInfo")
    public JsonResult<WelfareGoodsDetailVo> getGoodsInfo(Integer goodsId) {
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(welfareGoodsService.getGoodsInfoDetail(goodsId));
    }

    /**
     * 删除商品
     * @param goodsId 商品id
     * @author liuguanjun
     * @since 2021-12-17 11:25:38
     **/
    @GetMapping(value = "deleteGoods")
    public JsonResult<Integer> deleteGoods(Integer goodsId) {
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        WelfareGoods welfareGoods = new WelfareGoods();
        welfareGoods.setId(goodsId);
        welfareGoods.setStatus(CommonConstants.NO);
        welfareGoods.setUpdater(getAdminInfo().getId());
        welfareGoods.setUpdaterName(getAdminInfo().getUserName());
        welfareGoods.setUpdateTime(new Date());
        return JsonResult.success(welfareGoodsService.updateByPrimaryKeySelective(welfareGoods));
    }

    /**
     * 导入集采商品
     * @author liuguanjun
     * @date 2021-12-20 11:17:01
     **/
    @RequestMapping("/importJicaiGoodsList")
    public JsonResult<Integer> importJicaiGoodsList(HttpServletRequest request) throws Exception {
        LoginSysAdminVo adminInfo = getAdminInfo();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        //文件名规则 用户D:\\memberExcel\\时间戳_memberId.后缀
        if (EmptyUtils.isEmpty(items)) {
            return new JsonResult<>(null, HttpCode.ERROR);
        }
        String fileName = items.get(0).getName();
        if (EmptyUtils.isEmpty(fileName)) {
            return new JsonResult<>(null, 101, "请上传文件");
        }
        StringBuffer newFileName = new StringBuffer();
        newFileName.append(UploadConstant.excel_path)
                .append(System.currentTimeMillis())
                .append("_")
                .append(adminInfo.getId())
                .append(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
        File file = new File(newFileName.toString());
        if (file.exists()) {//文件存在就重新创建
            file.delete();
        }
        file = new File(newFileName.toString());
        file.createNewFile();
        InputStream is = items.get(0).getInputStream();
        //将原文件内容读取到目标文件
        OutputStream out = new FileOutputStream(file);
        try {
            int a = 0;
            while ((a = is.read()) != -1) {
                out.write(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JsonResult<List<List<String>>> data = ReadExcelUtil.readExcelInfo(file);
        if (data.getCode() != 200) {
            return new JsonResult<>(null, data.getCode(), data.getMsg());
        }
        return JsonResult.success(welfareGoodsService.importJicaiGoodsList(data.getData(), adminInfo));
    }


}
